package problems.practice;

import utils.beans.ListNode;

/**
 * 25. K 个一组翻转链表
 * https://leetcode.cn/problems/reverse-nodes-in-k-group/
 *
 * @author habitplus
 * @since 2022/8/13 16:45
 */
public class T25_1 {
    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null || head.next == null || k < 2) return head;

        ListNode tou = new ListNode(999, head);
        ListNode pre = tou, ass, l, r, tmp;
        int cnt = 1;

        while (head != null) {
            head = head.next;
            if (cnt == k) {
                // 翻转
                ass = pre.next;
                r = pre.next;
                l = null;
                while (ass != head) {
                    tmp = ass.next;
                    ass.next = l;
                    l = ass;
                    ass = tmp;
                }
                r.next = head;
                pre.next = l;
                pre = r;
                cnt = 1;
            } else {
                cnt++;
            }
        }

        return tou.next;
    }
}
